// UserManagementPanel.java 完整实现
package com.dw.gui.panel.user;

import com.dw.dao.user.UserDao;
import com.dw.model.user.*;
import com.dw.util.UIUtil;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.List;

public class UserManagementPanel extends JPanel {
    private JTable userTable;
    private JTextField tfSearch;
    private JButton btnEditPerm, btnResetPwd, btnDelete;
    private final User currentUser;

    public UserManagementPanel(User user) {
        this.currentUser = user;
        initUI();
        loadUserData("");
        setupButtons();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);

        // 头部面板
        JPanel headerPanel = createHeaderPanel();
        // 表格及滚动面板
        JScrollPane tableScrollPane = createTableScrollPane();
        tableScrollPane.setBackground(Color.WHITE);
        // 操作按钮面板
        JPanel buttonPanel = createButtonPanel();
        buttonPanel.setBackground(Color.WHITE);

        add(headerPanel, BorderLayout.NORTH);
        add(tableScrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private JPanel createHeaderPanel() {
        JPanel headerPanel = new JPanel(new BorderLayout(10, 0));
        headerPanel.setBackground(Color.WHITE);

        // 标题
        JLabel titleLabel = UIUtil.createTitleLabel("用户管理");
        titleLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        headerPanel.add(titleLabel, BorderLayout.WEST);

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        searchPanel.setBackground(Color.WHITE);

        tfSearch = UIUtil.createTextField();
        tfSearch.setColumns(10);
        JButton btnSearch = UIUtil.createButton("搜索");
        btnSearch.addActionListener(this::performSearch);

        searchPanel.add(UIUtil.createLabel("搜索用户:"));
        searchPanel.add(tfSearch);
        searchPanel.add(btnSearch);

        headerPanel.add(searchPanel, BorderLayout.EAST);
        return headerPanel;
    }

    private JScrollPane createTableScrollPane() {
        userTable = new JTable();
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userTable.getSelectionModel().addListSelectionListener(this::handleRowSelection);

        JScrollPane scrollPane = new JScrollPane(userTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("用户列表"));
        return scrollPane;
    }

    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonPanel.setBackground(Color.WHITE);

        JButton btnAdd = UIUtil.createButton("新建用户");
        btnAdd.addActionListener(this::showAddUserDialog);

        btnEditPerm = UIUtil.createButton("编辑权限");
        btnEditPerm.addActionListener(this::showPermissionDialog);

        btnResetPwd = UIUtil.createButton("重置密码");
        btnResetPwd.addActionListener(this::resetPassword);

        btnDelete = UIUtil.createButton("删除用户");
        btnDelete.addActionListener(this::deleteUser);

        buttonPanel.add(btnAdd);
        buttonPanel.add(btnEditPerm);
        buttonPanel.add(btnResetPwd);
        buttonPanel.add(btnDelete);
        return buttonPanel;
    }

    private void setupButtons() {
        boolean isAdmin = currentUser != null && currentUser.isAdmin();
        btnEditPerm.setEnabled(isAdmin);
        btnDelete.setEnabled(isAdmin);
        btnResetPwd.setEnabled(isAdmin);
    }

    // 数据加载部分
    private void loadUserData(String keyword) {
        new SwingWorker<List<User>, Void>() {
            @Override
            protected List<User> doInBackground() throws Exception {
                return new UserDao().searchUsers(keyword);
            }

            @Override
            protected void done() {
                try {
                    List<User> users = get();
                    DefaultTableModel model = new DefaultTableModel(
                            new Object[]{"用户ID", "用户名", "角色", "创建时间"}, 0
                    ) {
                        @Override
                        public boolean isCellEditable(int row, int column) {
                            return false;
                        }
                    };

                    for (User user : users) {
                        model.addRow(new Object[]{
                                user.getId(),
                                user.getUsername(),
                                user.getRole(),
                                user.getCreateTime()
                        });
                    }
                    userTable.setModel(model);
                    userTable.getColumnModel().getColumn(0).setMaxWidth(80);
                } catch (Exception e) {
                    UIUtil.showError(UserManagementPanel.this,
                            "加载用户数据失败: " + e.getMessage(), "数据库错误");
                }
            }
        }.execute();
    }

    // 事件处理方法
    private void performSearch(ActionEvent e) {
        loadUserData(tfSearch.getText().trim());
    }

    private void handleRowSelection(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            int selectedRow = userTable.getSelectedRow();
            boolean hasSelection = selectedRow != -1;
            btnEditPerm.setEnabled(hasSelection && currentUser.isAdmin());
            btnResetPwd.setEnabled(hasSelection && currentUser.isAdmin());
            btnDelete.setEnabled(hasSelection && currentUser.isAdmin());
        }
    }

    private void showAddUserDialog(ActionEvent e) {
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "新建用户", true);
        JPanel panel = new JPanel(new GridLayout(0, 2, 10, 10));

        JTextField tfUsername = new JTextField(20);
        JPasswordField pfPassword = new JPasswordField(20);
        JComboBox<String> cbRole = new JComboBox<>(new String[]{"doctor", "patient"});

        panel.add(new JLabel("用户名:"));
        panel.add(tfUsername);
        panel.add(new JLabel("密码:"));
        panel.add(pfPassword);
        panel.add(new JLabel("角色:"));
        panel.add(cbRole);

        JButton btnSubmit = new JButton("创建");
        btnSubmit.addActionListener(evt -> {
            User newUser = new User();
            newUser.setUsername(tfUsername.getText());
            newUser.setPassword(new String(pfPassword.getPassword()));
            newUser.setRole((String) cbRole.getSelectedItem());

            int userId = new UserDao().add(newUser);
            if (userId != -1) {
                loadUserData("");
                dialog.dispose();
                UIUtil.showInfo(this, "用户创建成功", "操作成功");
            } else {
                UIUtil.showError(this, "创建失败", "错误");
            }
        });

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(btnSubmit, BorderLayout.SOUTH);
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    private User getSelectedUser() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow == -1) return null;
        return new UserDao().findById((int) userTable.getValueAt(selectedRow, 0));
    }

    private void showPermissionDialog(ActionEvent e) {
        User selectedUser = getSelectedUser();
        if (selectedUser == null) return;

        PermissionDialog dialog = new PermissionDialog(selectedUser);
        dialog.setVisible(true);
    }

    private void resetPassword(ActionEvent e) {
        User selectedUser = getSelectedUser();
        if (selectedUser == null) return;

        String newPassword = JOptionPane.showInputDialog(this,
                "输入新密码:", "重置密码", JOptionPane.PLAIN_MESSAGE);

        if (newPassword != null && !newPassword.trim().isEmpty()) {
            new UserDao().updatePassword(selectedUser.getId(), newPassword);
            UIUtil.showInfo(this, "密码已重置", "操作成功");
        }
    }

    private void deleteUser(ActionEvent e) {
        User selectedUser = getSelectedUser();
        if (selectedUser == null) return;

        int confirm = JOptionPane.showConfirmDialog(this,
                "确定删除用户 " + selectedUser.getUsername() + "?",
                "确认删除", JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            try {
                new UserDao().deleteUser(selectedUser.getId());
                loadUserData("");
                UIUtil.showInfo(this, "用户已删除", "操作成功");
            } catch (SQLException ex) {
                UIUtil.showError(this, "删除失败: " + ex.getMessage(), "数据库错误");
            }
        }
    }


    public static class PermissionDialog extends JDialog {
        private final User targetUser;
        private final List<String> permissionList = List.of(
                "单据管理", "排班管理", "病案管理", "诊台管理", "发票管理",
                "费用管理", "用户管理", "其他"
        );
        private final JCheckBox[] permissionCheckBoxes;

        public PermissionDialog(User user) {
            setTitle("权限管理 - " + user.getUsername());
//            super((Frame) SwingUtilities.getWindowAncestor(UserManagementPanel.this),
//                    "权限管理 - " + user.getUsername(), true);
            this.targetUser = user;
            this.permissionCheckBoxes = new JCheckBox[permissionList.size()];
            initUI();
        }

        private void initUI() {
            setLayout(new BorderLayout(10, 10));
            setSize(400, 500);

            // 权限列表
            JPanel permissionPanel = new JPanel();
            permissionPanel.setLayout(new BoxLayout(permissionPanel, BoxLayout.Y_AXIS));

            // 创建勾选框并添加到面板
            for (int i = 0; i < permissionList.size(); i++) {
                String permission = permissionList.get(i);
                JCheckBox checkBox = new JCheckBox(permission);
                checkBox.setSelected(targetUser.hasPermission(permission));  // 根据当前权限设置勾选状态
                permissionCheckBoxes[i] = checkBox;
                permissionPanel.add(checkBox);
            }

            JScrollPane scrollPane = new JScrollPane(permissionPanel);
            add(scrollPane, BorderLayout.CENTER);

            // 操作按钮
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            JButton btnSave = UIUtil.createButton("保存");
            btnSave.addActionListener(e -> savePermissions());

            JButton btnCancel = UIUtil.createButton("取消");
            btnCancel.addActionListener(e -> dispose());

            buttonPanel.add(btnSave);
            buttonPanel.add(btnCancel);
            add(buttonPanel, BorderLayout.SOUTH);
        }

        private void savePermissions() {
            // 清空原有权限
            targetUser.getPermissions().clear();

            // 根据勾选框更新权限列表
            for (int i = 0; i < permissionCheckBoxes.length; i++) {
                if (permissionCheckBoxes[i].isSelected()) {
                    targetUser.getPermissions().add(permissionList.get(i));
                }
            }
            // 关闭对话框
            dispose();
        }
    }
}